<template>
  <el-container style="flex-direction:column;">
    <el-form :inline="true" :model="formInline" :rules="rules" ref="ruleForm" size="mini" class="demo-form-inline">
      <el-form-item label="" prop="username">
        <el-input v-model="formInline.username" placeholder="请输入名称搜索"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="success" icon="el-icon-search" @click="onSubmit">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="warning" icon="el-icon-refresh-left" @click="onReset" >重置</el-button>
      </el-form-item>
    </el-form> 
    <el-row style="padding-bottom: 10px;">
      <el-button v-if="getMenuListByPath.add" type="primary" size="mini" icon="el-icon-plus" @click="add">新增</el-button>
      <el-button v-if="getMenuListByPath.update" type="success" size="mini" icon="el-icon-edit" :disabled="multipleSelection.length !== 1" @click="handleEdit(null,multipleSelection[0])">修改</el-button>
      <el-button v-if="getMenuListByPath.delete" type="danger" size="mini" icon="el-icon-delete" :disabled="multipleSelection.length == 0" @click="deleteHandleClick">删除</el-button>
    </el-row>
    <el-table
      @selection-change="selectionChange"
      :data="allUserData.records" size="mini"
      style="width: 100%">
      <el-table-column align="center" header-align="center"
        type="selection" :selectable="selectable"
        width="55">
      </el-table-column>
      <el-table-column align="center" header-align="center"
        prop="username"
        label="账号">
      </el-table-column>
      <el-table-column align="center" header-align="center"
        prop="sex"
        label="性别">
      </el-table-column>
      <el-table-column v-if="getMenuListByPath.update || getMenuListByPath.delete" label="操作" width="160" align="center" header-align="center" fixed="right">
        <template slot-scope="scope">
          <el-dropdown size="mini" split-button type="primary" style="margin-right:3px;" trigger="click" v-if="getMenuListByPath.update">
            操作
            <el-dropdown-menu slot="dropdown" >
              <el-dropdown-item >
                <el-button
                    size="mini"  type="primary"
                    @click="handleEdit(scope.$index, scope.row)" >修改用户</el-button>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-button
                  size="mini"  type="primary"
                  @click="handleUpdatePassword(scope.$index, scope.row)">修改密码</el-button>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-popconfirm v-if="getMenuListByPath.delete"
            placement="top"
            confirm-button-text='确定'
            cancel-button-text='取消'
            icon="el-icon-delete"
            icon-color="red"
            title="确定删除本条数据吗？"
            @confirm="handleDelete(scope.$index, scope.row)"
          >
            <el-button
              size="mini" slot="reference"
              type="danger" icon="el-icon-delete"></el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination style="margin-top: 8px;"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="allUserData.current"
      :page-sizes="[5, 10, 20, 30]"
      :page-size="allUserData.size"
      layout="total, prev, pager, next, sizes,jumper"
      :total="allUserData.total">
    </el-pagination>
    <User_add_or_update_dialogVue 
      :form="nowUserData"
      :roleNameList="roleNameList"
      :title="title" 
      :visible.sync="visible" 
      @closeDialog="closeDialog"
      @operationFrom="operationFrom"
    ></User_add_or_update_dialogVue>
    <el-dialog title="修改密码" :visible.sync="updatePasswordDialog" :before-close="closeUpdatePasswordDialog">
      <el-form :model="updatePasswordForm" status-icon :rules="updatePasswordRules" ref="updatePasswordRuleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="密码" prop="pass">
          <el-input type="password" v-model="updatePasswordForm.pass" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass">
          <el-input type="password" v-model="updatePasswordForm.checkPass" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeUpdatePasswordDialog">取 消</el-button>
        <el-button type="primary" @click="updatePasswordDialogCommit">确 定</el-button>
      </span>
    </el-dialog>
  </el-container>
</template>

<script>
import User_add_or_update_dialogVue from "./components/User_add_or_update_dialog.vue";
import {getUserById,getUserByLikeUsername,updateUserPassword,deleteUserById,deleteUserByIdList} from '@/api/modules/SystemManagement/userManagement.js'
import { getAllRole } from "@/api/modules/SystemManagement/roleManagement";
export default {
  props:["getMenuListByPath"],
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (this.updatePasswordForm.checkPass !== '') {
          this.$refs.updatePasswordRuleForm.validateField('checkPass');
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.updatePasswordForm.pass) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      currentPage:1,
      formInline: {
        username: ''
      },
      multipleSelection: [],
      title:"",
      visible: false,
      allUserData:[],
      size:5,
      nowUserData:{},
      roleNameList:[],
      rules: {
        username:[
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ]
      },
      updatePasswordDialog:false,
      updatePasswordForm: {
        pass: '',
        checkPass: '',
        id:null
      },
      updatePasswordRules: {
        pass: [
          { validator: validatePass, trigger: 'blur' }
        ],
        checkPass: [
          { validator: validatePass2, trigger: 'blur' }
        ],
      }
    }
  },
  components:{
    User_add_or_update_dialogVue
  },
  created(){
    this.getAllUser(1,this.size);
  },
  methods: {
    onSubmit() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          this.getUserByLikeUsername(1,this.size,this.formInline.username);
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    //重置
    onReset() {
      this.$refs["ruleForm"].resetFields();
      this.getAllUser(1,this.size);
    },
    //删除按钮点击事件
    deleteHandleClick(){
      let data = [];
      for(let j=0 ; j < this.multipleSelection.length; j++) {
        data.push(this.multipleSelection[j].userId);
      }
      deleteUserByIdList(data).then(()=>{
        this.getAllUser(1,this.size);
      })
    },
    //table编辑用户按钮
    handleEdit(index, row) {
      // console.log(index, row);
      this.getUserById(row.userId);
      this.getAllRole();
      this.title="编辑用户";
      this.visible=true;
    },
    //修改密码按钮事件
    handleUpdatePassword(index, row){
      this.updatePasswordDialog=true;
      // console.log(index, row);
      this.updatePasswordForm.id = row.userId
    },
    //关闭修改密码dialog
    closeUpdatePasswordDialog(){
      this.updatePasswordDialog=false;
      this.updatePasswordForm.id = null;
      this.$refs["updatePasswordRuleForm"].resetFields();
    },
    //修改密码dialog提交事件
    updatePasswordDialogCommit(){
      this.$refs["updatePasswordRuleForm"].validate((valid) => {
        if (valid) {
          updateUserPassword({id: this.updatePasswordForm.id,password:this.updatePasswordForm.pass}).then(()=>{
            this.closeUpdatePasswordDialog()
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
     
    },
    //table删除按钮
    handleDelete(index, row) {
      // console.log(index, row);
      this.deleteUserById(row.userId);
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.size = val;
      this.getAllUser(1,val);
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.getAllUser(val,this.size);
    },
    //设置表格选择的列内容
    selectionChange(val){
      this.multipleSelection = val;
    },
    //打开dialog
    add(){
      this.nowUserData =  {
        "userId": null,
        "username":"",
        "sex":"男",
        "roleNameIdList":[]
      },
      this.getAllRole();
      this.title="新增用户";
      this.visible=true;
    },
    //关闭dialog
    closeDialog(){
      this.visible=false;
    },
    //操作dialog表单，刷新数据
    operationFrom(){
      this.visible=false;
      this.getAllUser(1,this.size);
    },
    //改变用户的状态
    changeStatus(val){
      console.log(val)
    },
    getAllUser(current,size){
      this.getUserByLikeUsername(current,size,this.formInline.username)
    },
    getUserById(id){
      getUserById({id:id}).then(res=>{
        this.nowUserData=res.data.data
      })
    },
    getAllRole(){
      getAllRole().then(res=>{
        this.roleNameList = res.data.data
      })
    },
    getUserByLikeUsername(current,size,username){
      getUserByLikeUsername({current:current,size:size,username:username}).then(res=>{
        this.allUserData = res.data.data
      })
    },
    deleteUserById(id){
      deleteUserById({id:id}).then(()=>{
        this.getAllUser(1,this.size);
      })
    },
    //表格复选框选择事件
    selectable(row){
      if(row.userId == 1){
        return false;
      }else{
        return true;
      }
    },
  } 
}
</script>

<style>

</style>